/**
 * 获取带过期时间的数据缓存
 * @param key
 * @returns
 */
export function getStorageWithExpire(key: string): Promise<string | undefined> {
  return new Promise((resolve, reject) => {
    uni.getStorage({
      key,
      success(res) {
        if (res.data) {
          const tempArray: Array<string> = res.data.split('|');
          const overtime: number = parseInt(tempArray[1]);
          if (isNaN(overtime)) {
            // 不存在过期时间
            resolve(res.data);
          } else {
            // 存在过期时间
            if (+new Date() < overtime) {
              resolve(decodeURIComponent(tempArray[0]));
            } else {
              // 已过期
              resolve(undefined);
              uni.removeStorage({
                key,
                fail: console.log,
              });
            }
          }
        }
      },
      fail: reject,
    });
  });
}

/**
 * 获取带过期时间的数据缓存
 * @param key
 * @returns
 */
export function getStorageSyncWithExpire(key: string): string | undefined {
  return uni.getStorageSync(key);
}

/**
 * 存储带过期时间的数据缓存
 * @param key
 * @param data
 * @param expire
 * @returns
 */
export function setStorageWithExpire(key: string, data: string | number, expire: number): Promise<void> {
  return new Promise((resolve, reject) => {
    const overtime = +new Date() + expire;
    uni.getStorage({
      key,
      data: `${encodeURIComponent(data)}|${overtime}`,
      success() {
        resolve();
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

/**
 * 设置带过期时间的数据缓存
 * @param key
 * @param data
 * @param expire
 * @returns
 */
export function setStorageSyncWithExpire(key: string, data: string | number, expire: number): void {
  const overtime = +new Date() + expire;
  const resData = `${encodeURIComponent(data)}|${overtime}`;
  return uni.setStorageSync(key, resData);
}

/**
 * 获取token
 * @returns
 */
export function getToken(): string | undefined {
  return getStorageSyncWithExpire('token');
}

/**
 * 设置token
 * @param token
 */
export function setToken(token: string) {
  return setStorageSyncWithExpire('token', token, 2 * 60 * 1000);
}
